package com.njwb.Swing.Login;

import com.njwb.Swing.MainFrame.MainFrame;
import com.njwb.Swing.Bill.BillView;
import com.njwb.Swing.Users.UserView;
import com.njwb.Swing.Supplier.SupplierView;
import com.njwb.Util.UtilService;

import javax.swing.*;

public class LoginController {
    private LoginView view;
    private LoginService loginService;

    public LoginController(LoginView view, LoginService loginService) {
        this.view = view;
        this.loginService = loginService;

        // 添加事件
        view.addLoginListener(e -> loginAction());
    }

    private void loginAction() {
        String username = view.getUsername();
        String password = view.getPassword();
        int role = view.getRole();

        String result = loginService.login(username, password, role);
        if ("登录成功".equals(result)) {
            view.showMessage("登录成功！", "提示",  JOptionPane.INFORMATION_MESSAGE);
            openMainFrame(role, username);
            view.dispose();
        } else {
            view.showMessage(result, "登录失败", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void openMainFrame(int role, String username) {
        // 初始化模块 View
        BillView billView = new BillView();
        UserView userView = new UserView();
        SupplierView supplierView = new SupplierView();

        // 创建 MainFrame
        MainFrame mainFrame = new MainFrame(username, role, billView, userView, supplierView);
        mainFrame.setTitle(role == 0 ? "普通员工主界面" : "经理主界面");
        mainFrame.setVisible(true);

        // 初始化模块 Controller，使用原来的 UtilService
        UtilService utilService = new UtilService();
        new com.njwb.Swing.Bill.BillController(billView, utilService);
        new com.njwb.Swing.Users.UserController(userView, utilService);
        new com.njwb.Swing.Supplier.SupplierController(supplierView, utilService);
    }
}
